package org.vehicle.service.redis;

import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;


@Service
public class RedisServiceImpl implements RedisService{
	
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

    /**
     * 设置 String
     * @param key
     * @param value
     */
    public void setString(String key ,String value){
    	try {
    		ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
    		valueOperations.set(key, value);
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
    }
    
    public void removeString(String key){
    	try {
    		redisTemplate.delete(key);
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
    }
     
    /**
     * 设置 过期时间
     * @param key
     * @param seconds 以秒为单位
     * @param value
     */
    public void setString(String key ,int seconds,String value){
        try {
        	ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        	valueOperations.set(key, value,seconds,TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
     
    /**
     * 获取String值
     * @param key
     * @return value
     */
    public String getString(String key){
    	try {
    		ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
    		return (String) valueOperations.get(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public void setSet(String key,String value){
    	try {
        	SetOperations<String, Object> setOperations =redisTemplate.opsForSet();
        	setOperations.add(key,value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    	
    }
    public void removeSet(String key,String value){
    	try {
        	SetOperations<String, Object> setOperations =redisTemplate.opsForSet();
        	setOperations.remove(key,value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    	
    }
    public Set<Object> getSet(String key){
    	try {
    		SetOperations<String, Object> setOperations =redisTemplate.opsForSet();
        	return setOperations.members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
